package com.tudouji.project.harvest.controller;

import com.alibaba.fastjson.JSONObject;
import com.tudouji.common.utils.poi.ExcelTempUtil;
import com.tudouji.framework.aspectj.lang.annotation.Log;
import com.tudouji.framework.aspectj.lang.enums.BusinessType;
import com.tudouji.framework.interceptor.annotation.RepeatSubmit;
import com.tudouji.framework.web.controller.BaseController;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.TableDataInfo;
import com.tudouji.project.bill.domain.Whinform;
import com.tudouji.project.bill.service.IWhinformService;
import com.tudouji.project.harvest.domain.*;
import com.tudouji.project.harvest.service.*;
import com.tudouji.project.pay.domain.Payinfo;
import com.tudouji.project.pay.domain.Payorderlist;
import com.tudouji.project.pay.service.IPayinfoService;
import com.tudouji.project.pay.service.IPayorderlistService;
import com.tudouji.project.quality.domain.Qarecord;
import com.tudouji.project.quality.service.IQarecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 货运单Controller
 *
 * @author wf
 * @date 2021-01-18
 */
@Slf4j
@RestController
@RequestMapping("/harvest/freightorder")
public class FreightorderController extends BaseController {
    @Autowired
    private IFreightorderService freightorderService;
    @Autowired
    private IPayinfoService payinfoService;
    @Autowired
    private IPayorderlistService payorderlistService;
    @Autowired
    private IQaformService qaformService;
    @Autowired
    private IQarecordService qarecordService;
    @Autowired
    private IWhinformService whinformService;
    @Autowired
    private IQaresultService qaresultService;
    @Autowired
    private IContstandardService contstandardService;
    @Autowired
    private IProcurementcontractService procurementcontractService;
    @Autowired
    private ExcelTempUtil excelTempUtil;

    /**
     * 查询货运单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Freightorder freightorder, String status, String functionType) {
        if (freightorder.getStatusList() == null){
            freightorder.setNostats(new Integer[]{0, -1});
        }
        List<Freightorder> list = freightorderService.selectFreightorderList(freightorder, status, functionType);
        Freightorder sum = freightorderService.selectFreightorderListSum(freightorder, status, functionType);
        return getDataTable(list, sum);
    }

    /**
     * 导出货运单列表
     */
    @PreAuthorize("@ss.hasPermi('harvest:freightorder:export')")
    @Log(title = "货运单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(@RequestBody Freightorder freightorder, String status, String functionType) {
        if (freightorder.getStatusList() == null || freightorder.getStatusList().length == 0){
            freightorder.setNostats(new Integer[]{0, -1});
        }
        List<Freightorder> list = freightorderService.selectFreightorderList(freightorder, status, functionType);
        return excelTempUtil.exportFreightOrder(list);
//        ExcelUtil<Freightorder> util = new ExcelUtil<>(Freightorder.class);
//        return util.exportExcel(list, "freightorder");
    }

    /**
     * 导出货运单入库单列表
     */
    @Log(title = "货运单", businessType = BusinessType.EXPORT)
    @GetMapping("/exportWhinformExport/{guids}")
    public AjaxResult exportWhinformExport(@PathVariable("guids") String guids) {
        AjaxResult result = freightorderService.exportWhinformExport(guids);
        return result;
    }

    /**
     * 获取货运单详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        try {
            JSONObject json = new JSONObject();
            Freightorder order = freightorderService.selectFreightorderDetailByAutoId(id);
            List<Qaresult> qaresults = qaresultService.selectQaresultByLinkId(order.getGuid());
            Qaform qaform = qaformService.selectQaformByLinkId(order.getGuid());
            Procurementcontract procurementcontract = procurementcontractService.selectProcurementcontractById(order.getContractid());
            Contstandard constant = new Contstandard();
            constant.setContractid(order.getContractid());
            List<Contstandard> constants = contstandardService.selectContstandardList(constant);

            BigDecimal price = BigDecimal.ZERO;
            BigDecimal awardamount = BigDecimal.ZERO;
            BigDecimal deductamount = BigDecimal.ZERO;
            if (order.getIsdiscount() == 6 && null != order.getAcceptStatus()) {
                if (1 == order.getAcceptStatus()) {
                    price = procurementcontract.getPrice();
                } else if (2 == order.getAcceptStatus()) {
                    for (int i = 0; i < constants.size(); i++) {
                        if (2 == constants.get(i).getType()) {
                            price = constants.get(i).getPrice();
                        }
                    }
                }
                for (int i = 0; i < qaresults.size(); i++) {
                    Qaresult re = qaresults.get(i);
                    if (1 == order.getAcceptStatus()) {
                        if (4 == re.getType()) {
                            continue;
                        }
                        if (null != re.getAwardamount()) {
                            awardamount = awardamount.add(re.getAwardamount());
                        }
                        if (null != re.getDeductamount()) {
                            deductamount = deductamount.add(re.getDeductamount());
                        }
                    } else {
                        if (4 == re.getType()) {
                            if (null != re.getAwardamount()) {
                                awardamount = awardamount.add(re.getAwardamount());
                            }
                            if (null != re.getDeductamount()) {
                                deductamount = deductamount.add(re.getDeductamount());
                            }
                        }
                    }
                }
            }

            Whinform whinform = new Whinform();
            whinform.setFoguid(order.getGuid());
            List<Whinform> whinforms = whinformService.findFreightWhin(whinform);
            if (whinforms.size() > 0) {
                json.put("whinform", whinforms.get(0));
            }
            json.put("msg", "success");
            json.put("order", order);
            json.put("contract", procurementcontract);
            json.put("qaresult", qaresults);//取土杂率（有奖罚）
            json.put("qaform", qaform);//取土杂率（无奖罚）、不合格率（无奖罚）
            json.put("constants", constants);//合同单价   合格薯  1800元/吨   淀粉薯  700元/吨
            json.put("price", price);//合同单价
            json.put("awardamount", awardamount);//奖励金额
            json.put("deductamount", deductamount);//扣罚金额
            return AjaxResult.success(json);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 新增货运单
     */
    @PreAuthorize("@ss.hasPermi('harvest:freightorder:add')")
    @Log(title = "货运单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Freightorder freightorder) {
        return toAjax(freightorderService.insertFreightorder(freightorder));
    }

    /**
     * 修改货运单
     */
    @PreAuthorize("@ss.hasPermi('harvest:freightorder:edit')")
    @Log(title = "货运单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Freightorder freightorder) {
        return toAjax(freightorderService.updateFreightorder(freightorder));
    }

    /**
     * 删除货运单
     */
    @PreAuthorize("@ss.hasPermi('harvest:freightorder:remove')")
    @Log(title = "货运单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{guids}")
    public AjaxResult remove(@PathVariable String[] guids) {
        return toAjax(freightorderService.deleteFreightorderByIds(guids));
    }

    @GetMapping("/getFreightorder/{payinfoguid}")
    public TableDataInfo getFreightorder(@PathVariable("payinfoguid") String payinfoguid) {
        Payinfo payinfo = payinfoService.selectPayinfoById(payinfoguid);
        if (2 == payinfo.getApplyType()) {
            payinfoguid = payinfo.getParentPayinfoGuid();
        }
        Payorderlist payorderlist = new Payorderlist();
        payorderlist.setPayinfoguid(payinfoguid);
        List<Payorderlist> payinfos = payorderlistService.selectPayorderlistList(payorderlist);
        FreightorderExport orders = new FreightorderExport();
        ArrayList<String> guids = new ArrayList<String>();
        for (int i = 0; i < payinfos.size(); i++) {
            payorderlist = payinfos.get(i);
            if (null != payorderlist) {
                guids.add(payorderlist.getFoguid());
            }
        }
        orders.setGuids(guids.toArray(new String[guids.size()]));
        startPage();
        List<FreightorderExport> list = freightorderService.selectFreightorder(orders);
        return getDataTable(list);
    }


    /**
     * 发起-扫码参数param
     **/
    @RepeatSubmit
    @PostMapping("/save")
    public AjaxResult save(@RequestParam(required = false) String param, Long contractid, String remark
            , @RequestParam(required = false) Long supplierId, @RequestParam(required = false) String fileIds, Integer sellformPayType) {
        return freightorderService.save(param, contractid, remark, supplierId, fileIds, sellformPayType);
    }

    /**
     * 手工卸货传id
     **/
    @RepeatSubmit
    @PostMapping("/discharge")
    public AjaxResult discharge(@RequestParam(required = false) Long id, String param) {
        return freightorderService.discharge(id, param);
    }

    /**
     * 审批
     **/
    @RepeatSubmit
    @PostMapping("/approval")
    public AjaxResult approval(Long id, Long taskid, String opinion, String fileIds) {
        return freightorderService.approval(id, taskid, opinion, fileIds);
    }

    /**
     * 价格确认
     **/
    @RepeatSubmit
    @PostMapping("/conformedPrice")
    public AjaxResult conformedPrice(Long id, Long taskid, String opinion, String fileIds, BigDecimal confirmedPrice) {

        return freightorderService.conformedPrice(id, taskid, opinion, fileIds, confirmedPrice);
    }

    /**
     * 价格审批
     **/
    @RepeatSubmit
    @PostMapping("/conformedPriceApproval")
    public AjaxResult conformedPriceApproval(Long id, Long taskid, String opinion, String fileIds) {

        return freightorderService.conformedPriceApproval(id, taskid, opinion, fileIds);
    }

    @RepeatSubmit
    @Log(title = "拒绝", businessType = BusinessType.OTHER)
    @PostMapping("/refuse")
    public AjaxResult refuse(Long taskid, Long id, String opinion, String fileIds, Long refuseNodeid, Long backUserid) {
        return freightorderService.refuse(id, fileIds, opinion, taskid, refuseNodeid, backUserid);
    }

    /**
     * 质检提交
     *
     * @param id
     * @param taskid
     * @param opinion
     * @param fileIds
     * @param refuseFlag       拒收
//     * @param unitPrice        淀粉属单价
     * @param deductRateByHand 手工输入的扣杂率
     * @return
     */
    @RepeatSubmit
    @PostMapping("/quality")
    public AjaxResult qa(Long id, Long taskid, String opinion, String fileIds, Integer refuseFlag
            /*, @RequestParam(required = false) BigDecimal unitPrice*/, BigDecimal deductRateByHand
            /*, @RequestBody Qaform qaform*/) {
        return freightorderService.quality(id, taskid, opinion, fileIds, refuseFlag/*, unitPrice*/, deductRateByHand/*, qaform*/);
    }

    /**
     * 收货确认
     *
     * @param id
     * @param taskid
     * @param opinion
     * @param fileIds
     * @param refuseFlag 拒收
     * @param cartype    车型
     * @param price      淀粉薯采收上传单价
     * @return  旧接口acceptance
     */
    @RepeatSubmit
    @PostMapping("/confirm")
    public AjaxResult confirm(Long id, Long taskid, String opinion, String fileIds, Integer refuseFlag, String cartype
            , @RequestParam(required = false) BigDecimal price, @RequestParam(required = false) BigDecimal unitPrice) {
        return freightorderService.confirm(id, taskid, opinion, fileIds, refuseFlag, cartype, price, unitPrice);
    }

    /**
     * 地头过磅
     **/
    @RepeatSubmit
    @PostMapping("/overWeightDT")
    public AjaxResult overWeightDT(Long id, Long taskid, String opinion, String fileIds, BigDecimal weight) {
        return freightorderService.overWeightDT(id, taskid, opinion, fileIds, weight);
    }

    /**
     * 入库过磅
     **/
    @RepeatSubmit
    @PostMapping("/overWeightYS")
    public AjaxResult overWeightYS(Long id, Long taskid, String opinion, String fileIds, BigDecimal weight) {
        return freightorderService.overWeightYS(id, taskid, opinion, fileIds, weight);
    }

    /**
     * 入库
     *
     * @hweight 入库重量 （毛重）
     * @pkgwgh 包装物重量
     * @wghtperpkg 每件毛重
     * @sthguid 库间guid
     **/
    @RepeatSubmit
    @PostMapping("/whin")
    public AjaxResult whin(Long id, Long taskid, String opinion, String fileIds, @RequestBody Freightorder freightorder) {
        log.info("hweight : " + freightorder.getHweight());
        return freightorderService.whin(id, taskid, opinion, fileIds, freightorder.getHweight(), freightorder.getPkgwgh()
                , freightorder.getWghtperpkg(), freightorder.getSthguid());
    }

    /**
     * 反入库
     **/
    @RepeatSubmit
    @PostMapping("/whinBack")
    public AjaxResult whinBack(Long id, Long taskid, String opinion, String fileIds) {
        return freightorderService.whinBack(id, taskid, opinion, fileIds);
    }

    /**
     * 微信--删除
     */
    @RepeatSubmit
    @Log(title = "删除", businessType = BusinessType.DELETE)
    @PostMapping("del")
    public AjaxResult remove(Long id) {
        return freightorderService.del(id);
    }


    /**
     * 扫码后更新位置信息
     */
    @RepeatSubmit
    @PostMapping("/saveLocation")
    public String saveLocation(String param) {
        log.info("扫码位置：" + param);
        return freightorderService.saveLocation(param);
    }

    /**
     * 获取质检项
     */
    @GetMapping("/getQaItems")
    public AjaxResult getQaItems(Long id) {
        return freightorderService.getQaItems(id);
    }

    /**
     * 获取质检详情
     */
    @GetMapping("/getQaDetail")
    public AjaxResult getQaDetail(Long id) {
        return qaformService.getQaDetail(id);
    }

    /**
     * 获取质检记录详情
     */
    @GetMapping("/getQaRecord")
    public AjaxResult getQaRecord(String guid) {
        return qarecordService.getQaRecord(guid);
    }

    /**
     * 每袋土豆的质检添加、修改
     */
    @RepeatSubmit
    @PostMapping("/updateRecord")
    public AjaxResult updateRecord(@RequestBody Qarecord qarecord) {
        return freightorderService.updateRecord(qarecord);
    }

    /**
     * 每袋土豆的质检删除
     */
    @RepeatSubmit
    @PostMapping("/delRecord")
    public AjaxResult delRecord(String guid) {
        return freightorderService.delRecord(guid);
    }
}
